package com.config;


import com.mapper.living.ManagerDao;
import com.util.ManagerUtil;
import living.com.domain.Admin;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * <p>
 *     管理员请求拦截
 * </p>
 * @author 大忽悠
 * @create 2022/2/20 11:48
 */
@Slf4j
@Component
@RequiredArgsConstructor
@RefreshScope
public class ManagerHandlerInterceptor extends HandlerInterceptorAdapter {
    private final ManagerDao managerDao;
    private static final PasswordEncoder encoder=new BCryptPasswordEncoder();
    @Value("${enable}")
    public Boolean enable;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("管理员请求的ip {}",request.getRemoteAddr());
        log.info("当前enable的值为: {}",enable);
        if(enable)
        {
            log.info("访问拦截已经开启");
            //请求头中是否包含特殊标记
            String dhy = request.getHeader("dhy");
            if(!dhy.equals(encoder.encode("dhyLikeXpy")))
            {
                throw new IllegalArgumentException("非法访问");
            }
        }
        log.info("管理员请求的资源 {}",request.getRequestURI());
        Integer u_id = Integer.valueOf(request.getHeader("m_id"));
        log.info("管理员id {}",request.getHeader("m_id"));
        //查找对应用户是否存在
        Admin admin = managerDao.getAdmin(u_id);
        Assert.notNull(admin,"拒绝访问");
        log.info("管理员如下: {}",admin.getUsername());
        ManagerUtil.setUser(admin);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求完毕,移除当前管理员信息
        ManagerUtil.removeUser();
    }
}
